<?php


namespace app\mini\controller;

// use app\BaseController as BaseController;
// use app\mini\model\Order as OrderModel;
use app\shop\model\Order as OrderModel;
use think\response\Json;
use think\facade\Db;
use Kingdee\Kingdee;
use app\shop\model\PayModel;

class Order extends Access
{


	//处理异常通联订单
    public function UptlOrder(){
        $this->param = request()->param();
        $payModel = new PayModel();
        $data = $payModel->UptlOrder($this->param);

    }

	/**
     * 订单列表
     * @return Json
     * @author SL
     * @create 2021-06-01
     */
    public function index(): Json
    {
    	$this->param = request()->param();
        $orderModel = new OrderModel();
        $this->param['customer_id'] = $this->customerId;
        $data = $orderModel->getDataList($this->param);
        return resultArray($data);
    }

    /**
     * 订单商品详情
     * @return Json
     * @author SL
     * @create 2021-06-02
     */
    public function detail(): Json
    {
    	$this->param = request()->param();
        $orderModel = new OrderModel();
        $data = $orderModel->getDataDetail($this->param);
        return resultArray($data);
    }

    /**
     * 确认订单
     * @return Json
     * @author SL
     * @create 2021-06-03
     */
    public function confirm(): Json
    {
        $this->param['list'] = request()->param('list');
        $this->param['customerId'] = $this->customerId;
        $orderModel = new OrderModel();
        $data       = $orderModel->confirmData($this->param);
        return resultArray($data);
    }

    //获取优惠券商品配置数据
    public function getYhjGoods(): Json
    {
        try {
            $this->param = request()->param();
            // 获取数据
            // $this->param['operator_id']   = $this->param['nurse_id'] ?? 0;
            // $this->param['operator_name'] = $this->param['nurse_id'];
            // 获取优惠券数据
            $yhj_id   = $this->param['yhj_id'] ?? 0;
            $customerYhj = Db::name('coupon_provide_customer')->where('id','=',$yhj_id)->find();
            // print_r($customerYhj);//exit();
            if (empty($this->param['nurse_id']) || empty($customerYhj)) {
                return resultArray(['error' => '参数错误']);
            }
            //获取优惠卷主表数据
            $yhjInfo = Db::name('coupon')->where('id','=',$customerYhj['coupon_id'])->find();
            if (empty($yhjInfo)) {
                return resultArray(['error' => '优惠卷不存在']);
            }
            //判断是否被使用
            if ($customerYhj['staus'] == 1) {
                return resultArray(['error' => '优惠券已被使用']);
            }
            // print_r($yhjInfo);exit;
            if ($yhjInfo['type'] != 4) {
                return resultArray(['error' => '优惠券类型错误']);
            }
            // 判断是否过期
            $nowTime = time();
            if ($yhjInfo['start_time']>$nowTime) {
                // code...
                return resultArray(['error' => '优惠券未到兑换时间']);
            }
            if ($yhjInfo['end_time']<=$nowTime) {
                // code...
                return resultArray(['error' => '优惠券已过期']);
            }
            $nurse_id = $this->param['nurse_id'] ?? 0;
            $nurseInfo = Db::name('shop_person')->where('id','=',$nurse_id)->find();
            if (empty($nurseInfo)) {
                // code...
                return resultArray(['error' => '员工信息不存在']);
            }
            // 获取店铺数据
            $shopInfo = Db::name('shop')->where('shop_id','=',$nurseInfo['shop_id'])->find();
            // 获取客户数据
            $customerTnfo = Db::name('customer')->where('id','=',$customerYhj['customer_id'])->find();

            if ($customerTnfo['shop_id'] != $nurseInfo['shop_id']) {
                // code...
                return resultArray(['error' => '非本店客户，无法核销']);
            }
            $goodsIds = $yhjInfo['goods_id'];
            if(empty($goodsIds)){
                return resultArray(['error' => '优惠券的商品不存在，无法核销']);
            }
            $goodsIdArray = explode(',',$goodsIds);
            $goodsList = Db::name('shop_goods')->where('id','in',$goodsIdArray)->field('id,name,is_project,spec_name')->select()->toArray();
            if(empty($goodsList)){
                return resultArray(['error' => '优惠券的商品不存在，无法核销']);
            }
            $data = [];
            $data['limit_number'] = $yhjInfo['limit_number'];
            $data['goodsList'] = $goodsList;
            return resultArray(['data'=>$data,'error' => '获取成功']);
        } catch (Exception $e) {
        }
         return resultArray(['error' => '核销失败，请稍后重试']);
    }
    /**
     * 创建订单
     * @return Json
     * @author SL
     * @create 2021-06-03
     */
    public function create(): Json
    {
    	$this->param = request()->param();
        // 获取数据
        // $this->param['operator_id']   = $this->param['nurse_id'] ?? 0;
        // $this->param['operator_name'] = $this->param['nurse_id'];
        // 获取优惠券数据
        // $data = [
        //         [
        //             'id'=>2,
        //             'is_project'=>0,
        //             'type'=>0,
        //             'start_time'=>'',
        //             'end_time'=>'',
        //             'num'=>'',
        //         ],[
        //             'id'=>3,
        //             'is_project'=>1,
        //             'type'=>1,
        //             'start_time'=>'2021-06-03 12:12',
        //             'end_time'=>'2021-06-03 12:12',
        //             'num'=>'3',
        //         ],[
        //             'id'=>4,
        //             'is_project'=>1,
        //             'type'=>1,
        //             'start_time'=>'',
        //             'end_time'=>'',
        //             'num'=>'3',
        //         ]
        //     ];
            // print_r(json_encode($data));exit;
        $yhj_id     = $this->param['yhj_id'] ?? 0;
        $goods_list   = $this->param['goods_list'] ?? '';
        // print_r($goods_list_str);exit;
        // $goods_list = json_decode($goods_list_str,true);
        // print_r($goods_list);exit;
        $customerYhj = Db::name('coupon_provide_customer')->where('id','=',$yhj_id)->find();
        // print_r($customerYhj);//exit();
        if (empty($this->param['nurse_id']) || empty($customerYhj)) {
            return resultArray(['error' => '参数错误']);
        }
        //获取优惠卷主表数据
        $yhjInfo = Db::name('coupon')->where('id','=',$customerYhj['coupon_id'])->find();
        if (empty($yhjInfo)) {
            return resultArray(['error' => '优惠卷不存在']);
        }
        //判断是否被使用
        if ($customerYhj['staus'] == 1) {
            return resultArray(['error' => '优惠券已被使用']);
        }
        if ($yhjInfo['type'] != 4) {
            return resultArray(['error' => '优惠券类型错误']);
        }
        // 判断是否过期
        $nowTime = time();
        if ($yhjInfo['start_time']>$nowTime) {
            // code...
            return resultArray(['error' => '优惠券未到兑换时间']);
        }
        if ($yhjInfo['end_time']<=$nowTime) {
            // code...
            return resultArray(['error' => '优惠券已过期']);
        }
        $nurse_id = $this->param['nurse_id'] ?? 0;
        // 获取员工数据
        $nurseInfo = Db::name('shop_person')->where('id','=',$nurse_id)->find();
        if (empty($nurseInfo)) {
            // code...
            return resultArray(['error' => '员工信息不存在']);
        }
        // 获取店铺数据
        $shopInfo = Db::name('shop')->where('shop_id','=',$nurseInfo['shop_id'])->find();
        // 获取客户数据
        $customerTnfo = Db::name('customer')->where('id','=',$customerYhj['customer_id'])->find();
        if ($customerTnfo['shop_id'] != $nurseInfo['shop_id']) {
            // code...
            return resultArray(['error' => '非本店客户，无法核销']);
        }
        // 获取订单商品数据
        $goodsIdArr = explode(',',$yhjInfo['goods_id']);
        $sqlyhjGoodsList  = Db::name('shop_goods')->where('id','in',$goodsIdArr)->select()->toArray();
        $yhjGoodsList = [];
        foreach ($sqlyhjGoodsList as $key => $val){
            $yhjGoodsList[$val['id']] = $val;
        }
        // 验证
        $data = [
            'uid'               => $customerTnfo['id'], // 客户
            'consignee'         => $customerTnfo['customer_name'], // 收货人
            'order_no'          => $this->getOrderNo(), // 订单号
            'sale_id'           => $nurse_id, // 销售员id
            'sale_name'         => $nurseInfo['name'], // 销售员姓名
            'shop_id'           => $shopInfo['shop_id'], // 门店id
            'shop_name'         => trim($shopInfo['shop_name']), // 门店名称
            'operator_id'       => $nurseInfo['id'],//制单员id
            'operator_name'     => $nurseInfo['name'],//制单员姓名
            'create_time'       => time(), // 创建时间
            'deal_time'         => time(), // 成交日期
            'goods_price'       => 0, // 订单标准金额
            'total_amount'      => 0, // 订单总金额
            'pay_amount'        => 0, // 实收本金
            'discount_amount'   => 0, // 订单优惠金额
            'gift_amount'       => 0, // 实收赠金
            'order_amount'      => 0, // 订单优惠金额
            'is_experience'     => 0, // 是否体验 0否 1是
            'experience_id'     => 0, // 体验人id
            'experience_name'   => '', // 体验人姓名
            'is_outreach'       => 0, // 是否外联 0否 1是
            'coupon_id'         => $yhjInfo['id'], // 优惠券id
            'coupon_name'       => $yhjInfo['name'], // 优惠券id
            'outreahc_id'       => 0, // 外联人id
            'outreahc_name'     => '', // 外联人姓名
            'is_introduction'   => 0, // 是否转介绍 0否 1是
            'introduction_id'   => 0, // 转介绍人id
            'introduction_name' => '', // 转介绍人姓名
            'description'       => '', // 订单描述
            'order_type'        => 2, // 订单类型 1新单 2补单
            'business_type'     => 1, // 业务类型 1项目 2疤痕
            'sales_policy'      => '', // 销售政策编码
            'market_id'         => $shopInfo['market_id'], // 市场id
            'market_name'       => $shopInfo['market_name'], // 市场名称
            'sales_organization'=> $shopInfo['market_kingdee_code'], // 销售组织编码
            'sales_name'        => $shopInfo['market_name'], // 销售组织名称
            'settlement_organization' => $shopInfo['market_name'], // 结算组织编码
            'settlement_name'         => $shopInfo['market_kingdee_code'], // 结算组织名称
            'delivery_name'       => $shopInfo['market_name'], // 发货部门名称
            'delivery_king'       => $shopInfo['market_kingdee_code'], // 发货部门编码
            'order_experience'        => 0 //订单是否有体验商品
        ];
        Db::startTrans();
        try {
            $orderId = Db::name('shop_order')->insertGetId($data);
            // $member_products = 0;
            $orderGoodsList = [];
            $serviceDataAll = [];
            if ($orderId) {
                foreach ($goods_list as $k => $v) {
                    $thisGoods = $yhjGoodsList[$v['id']] ?? [];
                    if(empty($thisGoods)){
                        continue;
                    }
                    $oneArr = [];
                    $oneArr['order_id']     = $orderId;
                    $oneArr['create_time']  = time();
                    $oneArr['goods_id']     = $thisGoods['id'];
                    $oneArr['goods_name']   = $thisGoods['name'];
                    $oneArr['kingdee_code'] = $thisGoods['kingdee_code'];
                    $oneArr['goods_price']  = $thisGoods['goods_price'];
                    $oneArr['pay_price']    = 0;
                    $oneArr['spec_name']    = $thisGoods['spec_name'];
                    $oneArr['unit_code']    = $thisGoods['unit_code'];
                    $oneArr['unit_name']    = $thisGoods['unit_name'];
                    $oneArr['number']       = $v['num'];
                    $oneArr['desc']         = '';
                    $oneArr['is_project']   = $thisGoods['is_project'];//是否服务 1 是 2否
                    $oneArr['category_id']  = $thisGoods['category_id'];
                    $oneArr['is_coupon_goods'] = 1;//是否优惠券商品 0否 1是
                    $project_type = $v['type'] ?1:0;
                    $oneArr['project_type'] = $project_type;//服务类型 1 按次 2按天
                    $oneArr['service_number'] = isset($v['num']) ? $v['num'] : 0;//服务次数
                    $oneArr['start_time']     = isset($v['start_time']) ? strtotime($v['start_time']) : 0;
                    $oneArr['end_time'] = isset($v['end_time']) ? strtotime($v['end_time']) : 0;
                    $oneArr['is_gift']  = 1;
                    $oneArr['house_code'] = $shopInfo['keycode'];
                    $oneArr['coupon_type'] = 4;//优惠券类型
                    $oneArr['house_code_name'] = $shopInfo['market_name'];
                    $oneArr['prestock_type'] = 1;
                    $oneArr['takeout_stock_num'] = 1;
                    // print_r($v);
                    array_push($orderGoodsList,$oneArr);
                    if($v['is_project'] == 2 && $v['id'] != 170 && $v['id'] != 171){
                        for($i=1;$i<=$orderGoodsList[$k]['number'];$i++){
                            $oneService['name']    = $oneArr['goods_name'];  //服务名称
                            $oneService['num']     = $oneArr['service_number'];   // 必填--服务类型：1按期2按次
                            $oneService['shop_id'] = $data['shop_id'];    // 店铺id
                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id
                            $oneService['service_type'] = $oneArr['project_type']==1?2:1;   // 必填--服务类型：1按期2按次
                            $oneService['start_time']   = $oneArr['start_time'];    // 类型为1是必填--服务开始时间
                            $oneService['end_time']     = $oneArr['end_time'];      // 类型为1是必填--服务开始时间
                            $oneService['experience']   = $data['is_experience'];     // 0否1是 是否体验
                            $oneService['kk_user_id']   = $data['sale_id'];     // 开卡人id
                            $oneService['kk_money']     = $data['total_amount'];       // 开卡金额
                            $oneService['goods_id']     = $oneArr['goods_id'];       // 开卡金额
                            $oneService['category_id']  = $oneArr['category_id'];       // 开卡金额
                            array_push($serviceDataAll,$oneService);
                        }
                    }
                }
            }else{
                return resultArray(['error' => '核销失败']);
            }
            Db::name('shop_order_goods')->insertAll($orderGoodsList);

                //添加操作记录
                // $goods_name = array_column($orderGoodsList, 'goods_name');
                // $goods_name_str = implode('|', $goods_name);
                // $content = '创建订单：【'. $nurseInfo['name'] . '】创建了【' . $customerTnfo['customer_name'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';
                // $code = [];
                // $code = $data;
                // $code['orderGoodsList']  = $orderGoodsList;
                // $this->addActionRecord($nurseInfo['id'],'shop_order_create',$orderId,$content,'shop','order',json_encode($code));
                // 处理客户的余额 //
                $customerModel = new \app\crm\model\Customer();
                $customer_id   = $data['uid'];    // 客户的id
                $balanceData   = [                // 余额变更数据集
                    // 'change_type'  => 2,      // 变动类型 1:增加 2:减少
                    // 'change_money' => $data['pay_amount'],      // 变更的本金
                    // 'complimentary_money' => $data['gift_amount'],  // 变更的赠金
                    // 'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目
                    ];
                $newOrderData  = [   // 新单变更数据集
                    // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳
                    // 'cj_money'    => $total_amount,    // 成交金额
                    // 'cj_order_id' => $orderId, // 成交的订单单号
                    ];
                $orderInfo     = [       // 本次需要新增的订单金额
                    // 'order_amount' => $total_amount, // 本次订单金额
                    // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳
                ];
                $member_products = 0; // 购买了几次会员商品
                $yhjOrderInfo  = [    // 本次需要处理的优惠卷
                    'yhj_id'     => $yhj_id??0,      // 本次优惠卷的id
                    'order_id'  => $orderId,   // 本次订单的id
                    'order_no'  => $data['order_no'],   // 本次订单的id
                    'operator_id' => $data['sale_id'],  // 核销人的id
                ];
                $customerModel->processingFunds($customer_id,$balanceData,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
                // print_r($serviceDataAll);exit;
                $customerModel->addCustomService($customer_id,$serviceDataAll);
                //处理成功，推送金蝶
                // exit;
                // 处理客户的余额 //
                // 客户推送金蝶
                if ($shopInfo['type'] == 1)
                {
                    $res = $customerModel->pushKingCustomer($customer_id);
                    if($res == false){
                        $error = $customerModel->getError();
                        return resultArray(['error' => $error]);
                    }
                    $kingDee = new Kingdee();
                    $result=$kingDee->send_order($orderId);
                    if ($result['code'])
                    {
                        $error = $result['msg'];
                        return resultArray(['error' => $error]);
                    }
                }
                Db::commit();
                $error = '创建成功';
                return resultArray(['data'=>[],'error' => $error]);
                // return true;
        }catch (\Exception $e) {
                Db::rollback();
                $error = $e->getMessage();
                // print_r($error);
                // return false;
        }
        return resultArray(['error' => $error]);
        // if (empty($orderGoodsList)) {
        //     // code...
        //     return resultArray(['error' => '无法获取商品数据，无法进行核销']);
        // }
        // Db::name('shop_order_goods')->insertAll($orderGoodsList);

        //     // 添加操作记录
        //     $goods_name = array_column($orderGoodsList, 'goods_name');
        //     $goods_name_str = implode('|', $goods_name);
        //     $content = '创建订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';
        //     $code = [];
        //     $code = $data;
        //     $code['orderGoodsList']  = $orderGoodsList;
        //     $this->addActionRecord($request['operator_id'],'shop_order_create',$orderId,$content,'shop','order',json_encode($code));
        //     // 处理客户的余额 //
        //     $customerModel = new \app\crm\model\Customer();
        //     $customer_id   = $data['uid'];    // 客户的id
        //     $balanceData   = [                // 余额变更数据集
        //         'change_type'  => 2,      // 变动类型 1:增加 2:减少
        //         'change_money' => $data['pay_amount'],      // 变更的本金
        //         'complimentary_money' => $data['gift_amount'],  // 变更的赠金
        //         'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目
        //         ];
        //     $newOrderData  = [   // 新单变更数据集
        //         // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳
        //         // 'cj_money'    => $total_amount,    // 成交金额
        //         // 'cj_order_id' => $orderId, // 成交的订单单号
        //         ];
        //     $orderInfo     = [       // 本次需要新增的订单金额
        //         // 'order_amount' => $total_amount, // 本次订单金额
        //         // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳
        //     ];
        //     // $member_products = 0; // 购买了几次会员商品
        //     $yhjOrderInfo  = [    // 本次需要处理的优惠卷
        //         'yhj_id '     => isset($request['yhj_id'])?$request['yhj_id']:0,      // 本次优惠卷的id
        //         'order_id  '  => $orderId,   // 本次订单的id
        //         'order_no  '  => $data['order_no'],   // 本次订单的id
        //         'operator_id' => $data['sale_id'],  // 核销人的id
        //     ];
        //     $customerModel->processingFunds($customer_id,$balanceData,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
        //     // print_r($serviceDataAll);exit;
        //     $customerModel->addCustomService($customer_id,$serviceDataAll);
        //     //处理成功，推送金蝶
        //     // exit;
        //     // 处理客户的余额 //
        //     // 客户推送金蝶
        //     if ($shop['type'] == 1)
        //     {
        //     $res = $customerModel->pushKingCustomer($customer_id);
        //     if($res == false){
        //         $this->error = $customerModel->getError();
        //         return false;
        //     }
        //         $kingDee = new Kingdee();
        //         $result=$kingDee->send_order($orderId);
        //         if ($result['code'])
        //         {
        //             $this->error = $result['msg'];
        //             return false;
        //         }
        //     }
        //     Db::commit();
        //     $this->error = '创建成功';
        //     return true;
    }

    /**
     * 生成订单号
     * @param  array $request 请求参数
     * @return String
     * @author SL
     * @create 2021-06-03
     */
    public function getOrderNo()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();
            if($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }
    /**
     * 修改订单状态
     * @return Json
     * @author SL
     * @create 2021-06-08
     */
    public function checkOrder(): Json
    {
    	$this->param = request()->param();
        $orderModel = new OrderModel();
        $data = $orderModel->checkOrderData($this->param);
        return resultArray($data);
    }

    /**
     * 支付
     * @param  OrderModel $orderModel
     * @return Json
     * @author Mr.Liu Wuchen
     * @create 2021-07-07 16:48
     */
    public function pay(OrderModel $orderModel): Json
    {
        $request                = request()->param();
        $request['customer_id'] = $this->customerId;
        $data = $orderModel->payOrder($request);
        return resultArray($data);
    }
}
